package com.yds.workmanager

import android.os.Bundle
import android.util.Log
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.AppCompatButton
import androidx.work.Constraints
import androidx.work.ExistingPeriodicWorkPolicy
import androidx.work.ExistingWorkPolicy
import androidx.work.NetworkType
import androidx.work.OneTimeWorkRequestBuilder
import androidx.work.PeriodicWorkRequestBuilder
import androidx.work.WorkInfo
import androidx.work.WorkManager
import androidx.work.workDataOf
import com.yds.workmanager.worker.DataSycWorker
import com.yds.workmanager.worker.ImageCompressWorker
import com.yds.workmanager.worker.ImageUploadWorker
import java.util.concurrent.TimeUnit

class WorkManagerActivity : AppCompatActivity() {
    private var workUniqueName = ""

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_work_manager)

        findViewById<AppCompatButton>(R.id.mBtnSynData).setOnClickListener {
            workUniqueName = "data_syc"
            val constraints = Constraints.Builder()
                .setRequiredNetworkType(NetworkType.CONNECTED)
                .setRequiresCharging(true)
                .build()
            val synRequest = PeriodicWorkRequestBuilder<DataSycWorker>(15, TimeUnit.MINUTES)
                .setConstraints(constraints)
                .build()
            WorkManager.getInstance(this).enqueueUniquePeriodicWork(workUniqueName, ExistingPeriodicWorkPolicy.KEEP, synRequest)
        }

        findViewById<AppCompatButton>(R.id.mBtnUploadLog).setOnClickListener {
            workUniqueName = "upload_log"
            val constraints = Constraints.Builder()
                .setRequiredNetworkType(NetworkType.CONNECTED)
                .setRequiresDeviceIdle(true)
                .build()
            val synRequest = OneTimeWorkRequestBuilder<DataSycWorker>()
                .setConstraints(constraints)
//                .setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 30, TimeUnit.SECONDS)
                .build()
            WorkManager.getInstance(this).enqueueUniqueWork(workUniqueName, ExistingWorkPolicy.KEEP, synRequest)
        }

        findViewById<AppCompatButton>(R.id.mBtnUploadImage).setOnClickListener {
            workUniqueName = "image_compress"
            val constraints = Constraints.Builder()
                .setRequiredNetworkType(NetworkType.CONNECTED)
                .build()
            val synRequestCompress = OneTimeWorkRequestBuilder<ImageCompressWorker>()
                .setInputData(workDataOf("image_path" to "sdcard/images/original.png"))
                .build()
            val synRequestUpload = OneTimeWorkRequestBuilder<ImageUploadWorker>()
                .setConstraints(constraints)
                .build()

            WorkManager.getInstance(this)
                .beginUniqueWork(workUniqueName, ExistingWorkPolicy.REPLACE, synRequestCompress)
                .then(synRequestUpload)
                .enqueue()

            // 监听压缩任务状态
            WorkManager.getInstance(this)
                .getWorkInfoByIdLiveData(synRequestCompress.id)
                .observe(this) { info ->
                    if (info?.state == WorkInfo.State.FAILED) {
                        Log.e("YDSimon", "压缩任务失败！")
                    }
                }

            // 监听上传任务状态
            WorkManager.getInstance(this)
                .getWorkInfoByIdLiveData(synRequestUpload.id)
                .observe(this) { info ->
                    if (info?.state == WorkInfo.State.FAILED) {
                        Log.e("YDSimon", "上传任务失败！")
                    }
                }

            WorkManager.getInstance(this).getWorkInfoByIdLiveData(synRequestUpload.id)
                .observe(this) { info ->
                    info?.let {
                        if (it.state == WorkInfo.State.SUCCEEDED) {
                            // 获取输出数据中的字符串
                            val resultString = it.outputData.getString("image_url")
                            Log.i("YDSimon", "上传图片结果: $resultString")
                        }
                    }
                }
        }

        findViewById<AppCompatButton>(R.id.mBtnCheckState).setOnClickListener {
            WorkManager.getInstance(this).getWorkInfosForUniqueWorkLiveData(workUniqueName)
                .observe(this) {
                    it.forEach { info ->
                        Log.i("YDSimon", "Work status: ${info.state}")
                    }
                }
        }

        findViewById<AppCompatButton>(R.id.mBtnCancelTask).setOnClickListener {
            WorkManager.getInstance(this).cancelUniqueWork(workUniqueName)
        }
    }
}